<?php

namespace app\index\model;

use think\Image;
use app\index\validate\Avatar as AvatarValidate;

class Upload
{

   /**
    * 保存上传图片
    * @Author   zhanghong(Laifuzi)
    * @DateTime 2019-02-21
    * @param    string             $image_method 图片上传模式
    * @param    File               $file         上传文件
    * @param    integer            $min_width    图片裁剪最小宽度
    * @return   object                           FunctionResult
    */
    static public function saveImage($image_method, $file, $min_width = 0){
        $res = new FunctionResult('保存上传文件失败');

        if($image_method == 'avatar'){
            $validate = new AvatarValidate;
            if(!$validate->check(['file' => $file])){
                $res->fail($validate->getError(), []);
                return $res;
            }
        }

        $local_dir = 'uploads';
        $ds = DIRECTORY_SEPARATOR;

        $info = $file->rule('md5')->move($local_dir);
        $save_name = $info->getSaveName();
        $save_path = $ds.$local_dir.$ds.$save_name;

        $image = Image::open('.'.$save_path);

        if($min_width > 0){
            //直接覆盖原图
            $image->thumb($min_width, $min_width)->save('.'.$save_path);
        }

        $data = [
            'ext' => $info->getExtension(),
            'save_path' => $save_path,
            'sha1' => $info->hash("sha1"),
            'md5' => $info->hash("md5"),
            'size' => $info->getSize(),
            'origin_name' => $file->getInfo('name'),
        ];
        $res->success('保存上传文件成功', $data);
        return $res;
    }
}
